import { Component, OnInit, OnDestroy, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router';
import { environment } from '../../../environments/environment';

// 定义活动接口
interface WorkflowActivity {
  id: string;
  type: string;
  name: string;
  properties: { [key: string]: any };
  position?: { x: number; y: number };
  connections?: string[];
}

// 定义活动类型接口
interface ActivityType {
  type: string;
  name: string;
  description: string;
  icon: string;
  color: string;
  category: string;
  properties: ActivityProperty[];
}

interface ActivityProperty {
  name: string;
  label: string;
  type: string;
  required: boolean;
  default?: any;
  options?: string[];
}

// 定义工作流表单接口
interface WorkflowForm {
  name: string;
  description: string;
  category: string;
  isPublished: boolean;
  activities: WorkflowActivity[];
  connections: WorkflowConnection[];
}

interface WorkflowConnection {
  id: string;
  source: string;
  target: string;
  label?: string;
}

@Component({
  selector: 'app-workflow-designer',
  templateUrl: './workflow-designer.component.html',
  styleUrls: ['./workflow-designer.component.scss']
})
export class WorkflowDesignerComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild('designerCanvas', { static: false }) designerCanvas!: ElementRef<HTMLCanvasElement>;
  @ViewChild('designerContainer', { static: false }) designerContainer!: ElementRef;
  
  workflowDefinitionId: string | null = null;
  isLoading = true;
  errorMessage = '';
  isEditMode = false;
  workflowDefinition: any = null;
  
  // 设计器状态
  isProfessionalMode = true;
  selectedActivity: WorkflowActivity | null = null;
  isDragging = false;
  isConnecting = false;
  connectionSource: WorkflowActivity | null = null;
  tempConnectionEnd = { x: 0, y: 0 };
  dragOffset = { x: 0, y: 0 };
  canvasOffset = { x: 0, y: 0 };
  zoom = 1;
  
  // 画布尺寸
  canvasWidth = 1200;
  canvasHeight = 800;

  // 工作流定义表单
  workflowForm: WorkflowForm = {
    name: '',
    description: '',
    category: 'DeviceRepair',
    isPublished: false,
    activities: [],
    connections: []
  };

  // 可用的活动类型
  availableActivities: ActivityType[] = [
    {
      type: 'Start',
      name: '开始',
      description: '工作流开始节点',
      icon: 'bi-play-circle-fill',
      color: '#28a745',
      category: 'control',
      properties: []
    },
    {
      type: 'End',
      name: '结束',
      description: '工作流结束节点',
      icon: 'bi-stop-circle-fill',
      color: '#dc3545',
      category: 'control',
      properties: []
    },
    {
      type: 'WriteLine',
      name: '输出消息',
      description: '在控制台输出一条消息',
      icon: 'bi-chat-text',
      color: '#6f42c1',
      category: 'console',
      properties: [
        { name: 'text', label: '消息内容', type: 'text', required: true }
      ]
    },
    {
      type: 'Delay',
      name: '延迟',
      description: '暂停工作流执行指定时间',
      icon: 'bi-clock',
      color: '#fd7e14',
      category: 'timing',
      properties: [
        { name: 'timeSpan', label: '延迟时间(秒)', type: 'number', required: true, default: 60 }
      ]
    },
    {
      type: 'HttpEndpoint',
      name: 'HTTP端点',
      description: '创建一个HTTP端点来触发工作流',
      icon: 'bi-globe',
      color: '#0dcaf0',
      category: 'http',
      properties: [
        { name: 'path', label: '路径', type: 'text', required: true },
        { name: 'method', label: '方法', type: 'select', options: ['GET', 'POST', 'PUT', 'DELETE'], default: 'POST', required: false }
      ]
    },
    {
      type: 'SendEmail',
      name: '发送邮件',
      description: '发送电子邮件通知',
      icon: 'bi-envelope',
      color: '#198754',
      category: 'notification',
      properties: [
        { name: 'to', label: '收件人', type: 'text', required: true },
        { name: 'subject', label: '主题', type: 'text', required: true },
        { name: 'body', label: '内容', type: 'textarea', required: true }
      ]
    },
    {
      type: 'SetVariable',
      name: '设置变量',
      description: '设置工作流变量的值',
      icon: 'bi-code-square',
      color: '#6610f2',
      category: 'data',
      properties: [
        { name: 'variableName', label: '变量名', type: 'text', required: true },
        { name: 'value', label: '值', type: 'text', required: true }
      ]
    },
    {
      type: 'Decision',
      name: '条件判断',
      description: '根据条件分支执行',
      icon: 'bi-diagram-3',
      color: '#20c997',
      category: 'control',
      properties: [
        { name: 'condition', label: '条件表达式', type: 'text', required: true },
        { name: 'trueLabel', label: '真值标签', type: 'text', default: 'True', required: false },
        { name: 'falseLabel', label: '假值标签', type: 'text', default: 'False', required: false }
      ]
    },
    {
      type: 'ParallelActivity',
      name: '并行执行',
      description: '并行执行多个分支',
      icon: 'bi-distribute-horizontal',
      color: '#e83e8c',
      category: 'control',
      properties: [
        { name: 'branchCount', label: '分支数量', type: 'number', default: 2, required: true }
      ]
    }
  ];

  // 活动类别
  activityCategories = [
    { id: 'control', name: '控制流', icon: 'bi-diagram-3' },
    { id: 'data', name: '数据处理', icon: 'bi-database' },
    { id: 'http', name: 'HTTP', icon: 'bi-globe' },
    { id: 'notification', name: '通知', icon: 'bi-bell' },
    { id: 'console', name: '控制台', icon: 'bi-terminal' },
    { id: 'timing', name: '定时', icon: 'bi-clock' }
  ];

  constructor(
    private http: HttpClient,
    private route: ActivatedRoute,
    private router: Router
  ) {}

  ngOnInit(): void {
    this.route.params.subscribe(params => {
      this.workflowDefinitionId = params['id'] || null;
      this.isEditMode = !!this.workflowDefinitionId;
      
      if (this.isEditMode) {
        this.loadWorkflowDefinition();
      } else {
        this.initializeNewWorkflow();
      }
    });
  }

  ngAfterViewInit(): void {
    // 只在专业模式下初始化Canvas
    if (this.isProfessionalMode) {
      this.initializeCanvas();
      this.setupCanvasEvents();
    }
    this.isLoading = false;
  }

  ngOnDestroy(): void {
    // 清理事件监听器
    if (this.designerCanvas?.nativeElement) {
      this.designerCanvas.nativeElement.removeEventListener('wheel', this.onCanvasWheel.bind(this));
    }
  }

  private initializeNewWorkflow(): void {
    this.workflowForm = {
      name: '新工作流',
      description: '描述您的工作流',
      category: 'DeviceRepair',
      isPublished: false,
      activities: [
        {
          id: 'start_' + Date.now(),
          type: 'Start',
          name: '开始',
          properties: {},
          position: { x: 100, y: 100 },
          connections: []
        }
      ],
      connections: []
    };
    this.isLoading = false;
  }

  private loadWorkflowDefinition(): void {
    if (!this.workflowDefinitionId) return;

    this.http.get(`${environment.apiUrl}/workflow-definitions/${this.workflowDefinitionId}`)
      .subscribe({
        next: (definition: any) => {
          this.workflowDefinition = definition;
          this.workflowForm = {
            name: definition.name || this.workflowDefinitionId,
            description: definition.description || '',
            category: 'DeviceRepair',
            isPublished: definition.isPublished || false,
            activities: this.parseActivities(definition),
            connections: this.parseConnections(definition)
          };
          this.isLoading = false;
        },
        error: (error) => {
          console.error('Failed to load workflow definition:', error);
          this.errorMessage = '无法加载工作流定义';
          this.isLoading = false;
        }
      });
  }

  private parseActivities(definition: any): WorkflowActivity[] {
    // 简化的活动解析 - 实际实现中需要解析工作流的JSON结构
    return [
      {
        id: 'start_loaded',
        type: 'Start',
        name: '开始',
        properties: {},
        position: { x: 100, y: 100 },
        connections: []
      }
    ];
  }

  private parseConnections(definition: any): WorkflowConnection[] {
    // 解析连接信息
    return [];
  }

  private initializeCanvas(): void {
    // 确保在专业模式下才初始化Canvas
    if (!this.isProfessionalMode) {
      return;
    }
    
    // 使用setTimeout确保DOM已完全渲染
    setTimeout(() => {
      if (!this.designerCanvas?.nativeElement) {
        console.warn('Canvas element not found, retrying...');
        setTimeout(() => this.initializeCanvas(), 100);
        return;
      }

      const canvas = this.designerCanvas.nativeElement;
      
      // 设置画布尺寸
      canvas.width = this.canvasWidth;
      canvas.height = this.canvasHeight;
      
      // 测试Canvas上下文
      const ctx = canvas.getContext('2d');
      if (!ctx) {
        console.error('Unable to get 2D context');
        return;
      }
      
      // 初始绘制
      this.redrawCanvas();
      console.log('Canvas initialized successfully');
    }, 0);
  }

  private setupCanvasEvents(): void {
    if (!this.isProfessionalMode || !this.designerCanvas?.nativeElement) {
      return;
    }
    
    const canvas = this.designerCanvas.nativeElement;
    
    // 鼠标事件
    canvas.addEventListener('mousedown', this.onCanvasMouseDown.bind(this));
    canvas.addEventListener('mousemove', this.onCanvasMouseMove.bind(this));
    canvas.addEventListener('mouseup', this.onCanvasMouseUp.bind(this));
    canvas.addEventListener('wheel', this.onCanvasWheel.bind(this));
    
    // 右键菜单事件
    canvas.addEventListener('contextmenu', (e) => {
      e.preventDefault(); // 阻止默认右键菜单
    });
    
    // 双击事件
    canvas.addEventListener('dblclick', this.onCanvasDoubleClick.bind(this));
    
    // 键盘事件
    canvas.addEventListener('keydown', this.onCanvasKeyDown.bind(this));
    canvas.tabIndex = 0; // 使canvas可以接收键盘事件
    
    console.log('Canvas events setup complete');
  }

  private onCanvasMouseDown(event: MouseEvent): void {
    if (!this.designerCanvas?.nativeElement) return;
    
    const rect = this.designerCanvas.nativeElement.getBoundingClientRect();
    const x = (event.clientX - rect.left - this.canvasOffset.x) / this.zoom;
    const y = (event.clientY - rect.top - this.canvasOffset.y) / this.zoom;
    
    const clickedActivity = this.getActivityAtPosition(x, y);
    
    // 右键点击或Shift+左键点击开始连接模式
    if (event.button === 2 || (event.button === 0 && event.shiftKey)) {
      event.preventDefault();
      if (clickedActivity) {
        this.isConnecting = true;
        this.connectionSource = clickedActivity;
        this.tempConnectionEnd = { x, y };
        console.log('开始连接模式，源节点:', clickedActivity.name);
      }
      return;
    }
    
    // 如果在连接模式下点击目标节点
    if (this.isConnecting && clickedActivity && this.connectionSource) {
      if (clickedActivity.id !== this.connectionSource.id) {
        this.connectActivities(this.connectionSource.id, clickedActivity.id);
        console.log('创建连接:', this.connectionSource.name, '->', clickedActivity.name);
      }
      this.isConnecting = false;
      this.connectionSource = null;
      this.redrawCanvas();
      return;
    }
    
    // 普通点击选择
    if (clickedActivity) {
      this.selectedActivity = clickedActivity;
      this.isDragging = true;
      this.dragOffset = {
        x: x - clickedActivity.position!.x,
        y: y - clickedActivity.position!.y
      };
    } else {
      this.selectedActivity = null;
      // 如果在连接模式下点击空白处，取消连接
      if (this.isConnecting) {
        this.isConnecting = false;
        this.connectionSource = null;
      }
    }
    
    this.redrawCanvas();
  }

  private onCanvasMouseMove(event: MouseEvent): void {
    if (!this.designerCanvas?.nativeElement) return;
    
    const rect = this.designerCanvas.nativeElement.getBoundingClientRect();
    const x = (event.clientX - rect.left - this.canvasOffset.x) / this.zoom;
    const y = (event.clientY - rect.top - this.canvasOffset.y) / this.zoom;
    
    // 如果在连接模式下，更新临时连接线终点
    if (this.isConnecting) {
      this.tempConnectionEnd = { x, y };
      this.redrawCanvas();
      return;
    }
    
    // 普通拖拽移动节点
    if (this.isDragging && this.selectedActivity) {
      this.selectedActivity.position = {
        x: x - this.dragOffset.x,
        y: y - this.dragOffset.y
      };
      this.redrawCanvas();
    }
  }

  private onCanvasMouseUp(event: MouseEvent): void {
    this.isDragging = false;
    // 连接模式在鼠标释放时不取消，需要点击目标或空白处才取消
  }

  private onCanvasWheel(event: WheelEvent): void {
    if (!this.designerCanvas?.nativeElement) return;
    
    event.preventDefault();
    
    const delta = event.deltaY > 0 ? 0.9 : 1.1;
    const newZoom = Math.max(0.1, Math.min(3, this.zoom * delta));
    
    if (newZoom !== this.zoom) {
      this.zoom = newZoom;
      this.redrawCanvas();
    }
  }

  private onCanvasDoubleClick(event: MouseEvent): void {
    if (!this.designerCanvas?.nativeElement) return;
    
    const rect = this.designerCanvas.nativeElement.getBoundingClientRect();
    const x = (event.clientX - rect.left - this.canvasOffset.x) / this.zoom;
    const y = (event.clientY - rect.top - this.canvasOffset.y) / this.zoom;
    
    // 在双击位置添加新活动
    this.addActivityAtPosition(x, y);
  }

  private onCanvasKeyDown(event: KeyboardEvent): void {
    switch (event.key) {
      case 'Escape':
        // 取消连接模式
        if (this.isConnecting) {
          this.isConnecting = false;
          this.connectionSource = null;
          this.redrawCanvas();
          console.log('取消连接模式');
        }
        break;
      case 'Delete':
        // 删除选中的节点
        if (this.selectedActivity) {
          this.removeSelectedActivity();
          console.log('删除选中节点');
        }
        break;
      case 'c':
        // Ctrl+C 开始连接模式
        if (event.ctrlKey && this.selectedActivity) {
          this.isConnecting = true;
          this.connectionSource = this.selectedActivity;
          console.log('开始连接模式 (Ctrl+C)');
        }
        break;
    }
  }

  private getActivityAtPosition(x: number, y: number): WorkflowActivity | null {
    const nodeSize = 80;
    
    for (const activity of this.workflowForm.activities) {
      if (!activity.position) continue;
      
      const dx = Math.abs(x - activity.position.x);
      const dy = Math.abs(y - activity.position.y);
      
      if (dx <= nodeSize / 2 && dy <= nodeSize / 2) {
        return activity;
      }
    }
    
    return null;
  }

  private addActivityAtPosition(x: number, y: number): void {
    // 默认添加一个 WriteLine 活动
    const defaultType = this.availableActivities.find(a => a.type === 'WriteLine');
    if (!defaultType) {
      console.error('Cannot find WriteLine activity type');
      return;
    }
    
    const newActivity: WorkflowActivity = {
      id: 'activity_' + Date.now(),
      type: defaultType.type,
      name: defaultType.name,
      properties: {},
      position: { x, y },
      connections: []
    };

    // 设置默认属性值
    if (defaultType.properties && Array.isArray(defaultType.properties)) {
      defaultType.properties.forEach((prop: ActivityProperty) => {
        if (prop && prop.name) {
          newActivity.properties[prop.name] = prop.default || '';
        }
      });
    }

    this.workflowForm.activities.push(newActivity);
    this.selectedActivity = newActivity;
    this.redrawCanvas();
  }

  public redrawCanvas(): void {
    if (!this.isProfessionalMode || !this.designerCanvas?.nativeElement) {
      return;
    }
    
    const canvas = this.designerCanvas.nativeElement;
    const ctx = canvas.getContext('2d');
    
    if (!ctx) {
      console.warn('Cannot get canvas context for redraw');
      return;
    }
    
    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 应用变换
    ctx.save();
    ctx.translate(this.canvasOffset.x, this.canvasOffset.y);
    ctx.scale(this.zoom, this.zoom);
    
    // 绘制网格
    this.drawGrid(ctx);
    
    // 绘制连接线
    this.drawConnections(ctx);
    
    // 绘制临时连接线（在连接模式下）
    if (this.isConnecting && this.connectionSource) {
      this.drawTempConnection(ctx);
    }
    
    // 绘制活动节点
    this.drawActivities(ctx);
    
    // 绘制连接点（在连接模式下）
    if (this.isConnecting) {
      this.drawConnectionPoints(ctx);
    }
    
    ctx.restore();
  }

  private drawGrid(ctx: CanvasRenderingContext2D): void {
    const gridSize = 20;
    const gridColor = '#f0f0f0';
    
    ctx.strokeStyle = gridColor;
    ctx.lineWidth = 1;
    
    // 垂直线
    for (let x = 0; x <= this.canvasWidth; x += gridSize) {
      ctx.beginPath();
      ctx.moveTo(x, 0);
      ctx.lineTo(x, this.canvasHeight);
      ctx.stroke();
    }
    
    // 水平线
    for (let y = 0; y <= this.canvasHeight; y += gridSize) {
      ctx.beginPath();
      ctx.moveTo(0, y);
      ctx.lineTo(this.canvasWidth, y);
      ctx.stroke();
    }
  }

  private drawConnections(ctx: CanvasRenderingContext2D): void {
    ctx.strokeStyle = '#6c757d';
    ctx.lineWidth = 2;
    
    for (const connection of this.workflowForm.connections) {
      const sourceActivity = this.workflowForm.activities.find(a => a.id === connection.source);
      const targetActivity = this.workflowForm.activities.find(a => a.id === connection.target);
      
      if (sourceActivity?.position && targetActivity?.position) {
        this.drawConnection(ctx, sourceActivity.position, targetActivity.position);
      }
    }
  }

  private drawConnection(ctx: CanvasRenderingContext2D, from: {x: number, y: number}, to: {x: number, y: number}): void {
    ctx.beginPath();
    ctx.moveTo(from.x, from.y);
    ctx.lineTo(to.x, to.y);
    ctx.stroke();
    
    // 绘制箭头
    const angle = Math.atan2(to.y - from.y, to.x - from.x);
    const arrowLength = 10;
    
    ctx.beginPath();
    ctx.moveTo(to.x, to.y);
    ctx.lineTo(
      to.x - arrowLength * Math.cos(angle - Math.PI / 6),
      to.y - arrowLength * Math.sin(angle - Math.PI / 6)
    );
    ctx.moveTo(to.x, to.y);
    ctx.lineTo(
      to.x - arrowLength * Math.cos(angle + Math.PI / 6),
      to.y - arrowLength * Math.sin(angle + Math.PI / 6)
    );
    ctx.stroke();
  }

  private drawActivities(ctx: CanvasRenderingContext2D): void {
    const nodeSize = 80;
    
    for (const activity of this.workflowForm.activities) {
      if (!activity.position) continue;
      
      const activityType = this.getActivityType(activity.type);
      const isSelected = this.selectedActivity?.id === activity.id;
      
      // 绘制节点背景
      ctx.fillStyle = activityType?.color || '#6c757d';
      if (isSelected) {
        ctx.strokeStyle = '#0d6efd';
        ctx.lineWidth = 3;
      } else {
        ctx.strokeStyle = '#dee2e6';
        ctx.lineWidth = 2;
      }
      
      const radius = nodeSize / 2;
      ctx.beginPath();
      ctx.roundRect(
        activity.position.x - radius,
        activity.position.y - radius,
        nodeSize,
        nodeSize,
        10
      );
      ctx.fill();
      ctx.stroke();
      
      // 绘制文本
      ctx.fillStyle = 'white';
      ctx.font = '12px sans-serif';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText(
        activity.name,
        activity.position.x,
        activity.position.y + 5
      );
      
      // 绘制图标（简化为文本）
      ctx.font = '16px sans-serif';
      ctx.fillText(
        activityType?.type.charAt(0) || '?',
        activity.position.x,
        activity.position.y - 10
      );
    }
  }

  // 添加活动到画布
  addActivity(activityType: ActivityType): void {
    if (!activityType) {
      console.error('ActivityType is null or undefined');
      return;
    }
    
    const newActivity: WorkflowActivity = {
      id: 'activity_' + Date.now(),
      type: activityType.type,
      name: activityType.name,
      properties: {},
      position: { 
        x: 200 + Math.random() * 400, 
        y: 150 + Math.random() * 300 
      },
      connections: []
    };

    // 设置默认属性值
    if (activityType.properties && Array.isArray(activityType.properties)) {
      activityType.properties.forEach((prop: ActivityProperty) => {
        if (prop && prop.name) {
          newActivity.properties[prop.name] = prop.default || '';
        }
      });
    }

    this.workflowForm.activities.push(newActivity);
    this.redrawCanvas();
  }

  // 删除选中的活动
  removeSelectedActivity(): void {
    if (!this.selectedActivity) return;
    
    const index = this.workflowForm.activities.findIndex(a => a.id === this.selectedActivity!.id);
    if (index >= 0) {
      this.workflowForm.activities.splice(index, 1);
      // 删除相关连接
      this.workflowForm.connections = this.workflowForm.connections.filter(
        c => c.source !== this.selectedActivity!.id && c.target !== this.selectedActivity!.id
      );
      this.selectedActivity = null;
      this.redrawCanvas();
    }
  }

  // 连接两个活动
  connectActivities(sourceId: string, targetId: string): void {
    // 检查连接是否已存在
    const existingConnection = this.workflowForm.connections.find(
      c => c.source === sourceId && c.target === targetId
    );
    
    if (!existingConnection) {
      this.workflowForm.connections.push({
        id: 'connection_' + Date.now(),
        source: sourceId,
        target: targetId
      });
      this.redrawCanvas();
    }
  }

  // 切换设计器模式
  toggleDesignerMode(): void {
    this.isProfessionalMode = !this.isProfessionalMode;
    
    // 如果切换到专业模式，需要初始化Canvas
    if (this.isProfessionalMode) {
      // 使用延迟确保DOM更新完成
      setTimeout(() => {
        this.initializeCanvas();
        this.setupCanvasEvents();
      }, 100);
    }
  }

  // 缩放控制
  zoomIn(): void {
    this.zoom = Math.min(3, this.zoom * 1.2);
    this.redrawCanvas();
  }

  zoomOut(): void {
    this.zoom = Math.max(0.1, this.zoom / 1.2);
    this.redrawCanvas();
  }

  resetZoom(): void {
    this.zoom = 1;
    this.canvasOffset = { x: 0, y: 0 };
    this.redrawCanvas();
  }

  // 自动布局
  autoLayout(): void {
    const activities = this.workflowForm.activities;
    const spacing = 150;
    let currentY = 100;
    
    activities.forEach((activity, index) => {
      activity.position = {
        x: 200 + (index % 3) * spacing,
        y: currentY + Math.floor(index / 3) * spacing
      };
    });
    
    this.redrawCanvas();
  }

  // 现有方法保持不变
  removeActivity(index: number): void {
    this.workflowForm.activities.splice(index, 1);
    this.redrawCanvas();
  }

  moveActivityUp(index: number): void {
    if (index > 0) {
      const activity = this.workflowForm.activities[index];
      this.workflowForm.activities.splice(index, 1);
      this.workflowForm.activities.splice(index - 1, 0, activity);
    }
  }

  moveActivityDown(index: number): void {
    if (index < this.workflowForm.activities.length - 1) {
      const activity = this.workflowForm.activities[index];
      this.workflowForm.activities.splice(index, 1);
      this.workflowForm.activities.splice(index + 1, 0, activity);
    }
  }

  getActivityType(typeName: string): ActivityType | undefined {
    return this.availableActivities.find(a => a.type === typeName);
  }

  getActivitiesByCategory(category: string): ActivityType[] {
    return this.availableActivities.filter(a => a.category === category);
  }

  saveWorkflow(): void {
    if (!this.workflowForm.name.trim()) {
      alert('请输入工作流名称');
      return;
    }

    const workflowData = this.buildWorkflowDefinition();
    
    if (this.isEditMode) {
      this.updateWorkflow(workflowData);
    } else {
      this.createWorkflow(workflowData);
    }
  }

  private buildWorkflowDefinition(): any {
    // 构建Elsa工作流定义JSON
    const activities = this.workflowForm.activities.map((activity, index) => {
      const activityType = this.getActivityType(activity.type);
      const elsaActivity: any = {
        id: activity.id,
        type: `Elsa.${activity.type}`,
        name: activity.name,
        properties: {},
        position: activity.position
      };

      // 转换属性
      Object.keys(activity.properties).forEach(key => {
        const value = activity.properties[key];
        if (value) {
          elsaActivity[key] = {
            typeName: 'String',
            expression: {
              type: 'Literal',
              value: value
            }
          };
        }
      });

      return elsaActivity;
    });

    return {
      name: this.workflowForm.name,
      description: this.workflowForm.description,
      definitionId: this.workflowDefinitionId || `workflow_${Date.now()}`,
      version: 1,
      isLatest: true,
      isPublished: this.workflowForm.isPublished,
      activities: activities,
      connections: this.workflowForm.connections,
      root: {
        type: 'Elsa.Sequence',
        activities: activities
      }
    };
  }

  private createWorkflow(workflowData: any): void {
    console.log('Creating workflow:', workflowData);
    // 这里应该调用后端API创建工作流
    alert('工作流创建功能正在开发中\n\n工作流定义：\n' + JSON.stringify(workflowData, null, 2));
  }

  private updateWorkflow(workflowData: any): void {
    console.log('Updating workflow:', workflowData);
    // 这里应该调用后端API更新工作流
    alert('工作流更新功能正在开发中\n\n工作流定义：\n' + JSON.stringify(workflowData, null, 2));
  }

  publishWorkflow(): void {
    this.workflowForm.isPublished = true;
    this.saveWorkflow();
  }

  goBack(): void {
    this.router.navigate(['/workflows']);
  }

  // 打开外部Elsa Studio
  openElsaStudio(): void {
    const elsaUrl = 'http://localhost:13000';
    window.open(elsaUrl, '_blank');
  }

  // 获取活动名称
  getActivityName(activityId: string): string {
    const activity = this.workflowForm.activities.find(a => a.id === activityId);
    return activity ? activity.name : '未知节点';
  }

  // 删除连接
  removeConnection(index: number): void {
    this.workflowForm.connections.splice(index, 1);
    this.redrawCanvas();
  }

  // 复制活动
  duplicateActivity(): void {
    if (!this.selectedActivity) return;

    const newActivity: WorkflowActivity = {
      ...this.selectedActivity,
      id: 'activity_' + Date.now(),
      name: this.selectedActivity.name + ' (副本)',
      position: {
        x: this.selectedActivity.position!.x + 100,
        y: this.selectedActivity.position!.y + 50
      },
      properties: { ...this.selectedActivity.properties },
      connections: []
    };

    this.workflowForm.activities.push(newActivity);
    this.selectedActivity = newActivity;
    this.redrawCanvas();
  }

  private drawTempConnection(ctx: CanvasRenderingContext2D): void {
    if (!this.connectionSource?.position) return;
    
    ctx.strokeStyle = '#0d6efd';
    ctx.lineWidth = 3;
    ctx.setLineDash([5, 5]); // 虚线效果
    
    ctx.beginPath();
    ctx.moveTo(this.connectionSource.position.x, this.connectionSource.position.y);
    ctx.lineTo(this.tempConnectionEnd.x, this.tempConnectionEnd.y);
    ctx.stroke();
    
    ctx.setLineDash([]); // 重置线型
  }

  private drawConnectionPoints(ctx: CanvasRenderingContext2D): void {
    // 为所有节点绘制连接点指示器
    for (const activity of this.workflowForm.activities) {
      if (!activity.position) continue;
      
      const isSource = this.connectionSource?.id === activity.id;
      
      // 绘制连接点
      ctx.fillStyle = isSource ? '#28a745' : '#0d6efd';
      ctx.beginPath();
      ctx.arc(activity.position.x, activity.position.y, 6, 0, Math.PI * 2);
      ctx.fill();
      
      // 为源节点添加额外的视觉效果
      if (isSource) {
        ctx.strokeStyle = '#ffffff';
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.arc(activity.position.x, activity.position.y, 8, 0, Math.PI * 2);
        ctx.stroke();
      }
    }
  }
}
